package it.koutifaris.travianmap.info;

import it.koutifaris.travianmap.model.Tribe;

import java.util.regex.Pattern;

class TroopFileParser {

	private final String SPLIT_REGEX = "\\t+";
	private final Pattern pattern;

	public TroopFileParser() {
		pattern = Pattern.compile(SPLIT_REGEX);
	}

	public boolean skipLine(String line) {
		return line.trim().equals("") || line.trim().startsWith("//");
	}

	public Troop parseLine(String line) {
		String[] values = pattern.split(line);

		String name = values[0];
		int offence = Integer.parseInt(values[1]);
		int infantryDefence = Integer.parseInt(values[2]);
		int cavalryDefence = Integer.parseInt(values[3]);
		// Skip 4th entry, not needed
		int speed = Integer.parseInt(values[5]);
		TroopType type = getType(values[6]);
		Tribe tribe = getTribe(values[7]);

		return new TroopImpl(name, tribe, type, offence, cavalryDefence, infantryDefence, speed);
	}

	private Tribe getTribe(String tribeName) {
		Tribe[] values = Tribe.values();
		for (Tribe tribe : values) {
			if (tribe.name().equals(tribeName)) {
				return tribe;
			}
		}

		throw new IllegalArgumentException(tribeName + " is not a valid " + Tribe.class.getSimpleName());
	}

	private TroopType getType(String type) {
		TroopType[] values = TroopType.values();
		for (TroopType troopType : values) {
			if (troopType.name().equals(type)) {
				return troopType;
			}
		}

		throw new IllegalArgumentException(type + " is not a valid " + TroopType.class.getSimpleName());
	}
}
